using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

[AddComponentMenu("TagMachine/Game Modes/HIPS")]
public class GameModeHIPS : GameModeClassic 
{
	public GameObject AIPrefab 	= null;
	public int NumAI 			= 10;

	public bool PlayWithTrails 	= false;
	public Color PlayersColor 	= Color.blue;

	// Initialization
	protected override void SetupFromPreferences()
	{
		base.SetupFromPreferences();

		if ( PlayerPrefs.HasKey( "NumAI" ) )
		{
			NumAI = PlayerPrefs.GetInt( "NumAI" );
		}
		if ( PlayerPrefs.HasKey( "PlayWithTrails" ) )
		{
			PlayWithTrails = PlayerPrefs.GetInt( "PlayWithTrails" ) == 0 ? false : true;
		}
	}

	protected override void ClearPreferences()
	{
		base.ClearPreferences();
		
		PlayerPrefs.DeleteKey( "NumAI" );
		PlayerPrefs.DeleteKey( "PlayWithTrails" );
	}

	protected override void Awake()
	{
		base.Awake();

		GameObject[] SpawnPoints 	= GameObject.FindGameObjectsWithTag( SpawnPointTag );
		if ( SpawnPoints == null || SpawnPoints.Length == 0 )
		{
			Debug.LogWarning("No SpawnPoints found!!!");
			return;
		}

		for ( int i = 0; i < NumAI; ++i )
		{
			int ChosenSpawnPoint = UnityEngine.Random.Range(0, SpawnPoints.Length);
			GameObject NewAI 	= Instantiate( AIPrefab,
												SpawnPoints[ChosenSpawnPoint].transform.position,
												Quaternion.Euler( 0.0f,UnityEngine.Random.Range(0.0f, 360.0f), 0.0f ) ) as GameObject;

			NewAI.renderer.material.color = PlayersColor;

			EntityTrailGenerator TrailGen = NewAI.GetComponent<EntityTrailGenerator>();
			TrailGen.Setup( PlayersColor, NewAI.GetComponent<NavMeshAgent>() );
			TrailGen.enabled = PlayWithTrails;
		}
	}

	protected override void Start()
	{
		// Change all player colors
		for ( int i = 0; i < PlayerColors.Length; ++i )
		{
			PlayerColors[i] = PlayersColor;
		}

		base.Start();

		for (int i = 0; i < m_Players.Length; ++i )
		{
			m_Players[i].GetComponentInChildren< EntityTrailGenerator >().enabled = PlayWithTrails;
		}
	}
}
